﻿using System;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class CompositeTerm : Term {
        public string Name;
        public Dictionary<string, Term> SubTerms;

        public CompositeTerm (string name) {
            Name = name;
            SubTerms = new Dictionary<string, Term> ();
        }

        public void Add (string name, Term term, bool isMultiple) {
            if (!isMultiple) {
                if (!SubTerms.ContainsKey (name)) {
                    SubTerms.Add (name, term);
                } else {
                    throw new NamedRuleAlreadySetException (name);
                }
            } else {
                AddMuliple (name, term);
            }
        }

        private void AddMuliple (string name, Term term) {
            Term foundTerm;
            ListTerm listTerm;
            if (!SubTerms.TryGetValue (name, out foundTerm)) {
                listTerm = new ListTerm ();
                SubTerms.Add (name, listTerm);
            } else {
                if (foundTerm is ListTerm) {
                    listTerm = foundTerm as ListTerm;
                } else {
                    throw new NamedListRuleAlreadySetException (name);
                }
            }

            listTerm.Terms.Add (term);
        }
    }

    public class NamedRuleAlreadySetException : Exception {
        public readonly string Name;

        public NamedRuleAlreadySetException (string name)
            : base ("named rule `" + name + "' already set in results") {
            Name = name;
        }
    }

    public class NamedListRuleAlreadySetException : Exception {
        public readonly string Name;

        public NamedListRuleAlreadySetException (string name)
            : base ("named rule `" + name + "' already set and not a list in results") {
            Name = name;
        }
    }
}